package com.sweet.mealon.face.daily.lock.reentrantlock;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: crazier.huang
 * @project: faceDaily
 * @date: 2021/4/29 星期四
 * @desc:
 */
public class ReentrantReadWrite {

    private static volatile HashMap<String, String> hashMap = new HashMap<String, String>();

    final static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public  void put(String key, String o) {
        lock.writeLock().lock();
        try {
            System.out.println(String.format("%s get write work，thread name %s", key, Thread.currentThread().getName()));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public  void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(String.format("%s get read work，thread name %s", key, Thread.currentThread().getName()));
        } finally {
            lock.readLock().unlock();
        }


    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantReadWrite rw = new ReentrantReadWrite();

        for (int i = 0; i < 100; i++) {
            Thread writeThread = new Thread(new ReentrantWriteThread(rw, String.valueOf(i)));
            writeThread.start();
            Thread readThread = new Thread(new ReentrantReadThread(rw, String.valueOf(i)));
            readThread.start();
        }
        TimeUnit.SECONDS.sleep(5);
    }

}
